var hx = require("hbuilderx");
const rules = require('./rules.js')
let triggerString = ''
let languages = []
//该方法将在插件激活的时候调用
function activate(context) {
	triggerString = hx.workspace.getConfiguration('any-rule').get('triggerString')
	languages = hx.workspace.getConfiguration('any-rule').get('language').split(',').map(item =>
		({ language: item }))

	const inlineProvider = (document, position, context, token) => {
		const line = document.lineAt(position);
		const prefix = line.text.substring(0, position.character)
		if (prefix.endsWith(triggerString)) {
			showRulesPcik(true)
		}

		return [];
	}
	let configurationChangeDisplose = hx.workspace.onDidChangeConfiguration(function(event) {
		triggerString = hx.workspace.getConfiguration('any-rule').get('triggerString')
		languages = hx.workspace.getConfiguration('any-rule').get('language').split(',').map(item =>
			({ language: item }))
	});


	const disposable = hx.languages.registerInlineCompletionItemProvider(
		languages, {
			provideInlineCompletionItems: inlineProvider
		}
	)
	context.subscriptions.push(disposable)
	let commondRule = hx.commands.registerCommand('extension.rule', () => {
		showRulesPcik()
	});
	//订阅销毁钩子，插件禁用的时候，自动注销该command。
	context.subscriptions.push(commondRule);
}


async function showRulesPcik(isTiggter = false, position) {
	let editor = await hx.window.getActiveTextEditor();
	if (!editor) {
		return
	}
	const userSelectd = await hx.window.showQuickPick(
		rules.map(({ examples, title, rule }) => {
			return {
				label: title,
				rule: String(rule),
				detail: `例如: ${examples.join(' 或 ')}`
			}
		}), {
			placeHolder: '请输入关键词'
		}
	)

	if (isTiggter) {
		let linePromise = editor.document.lineFromPosition(editor.selection.active);
		linePromise.then((line) => {
			const index = line.text.indexOf(triggerString)
			const triggerStringLength = triggerString.length
			editor.setSelection(line.start + index, line.start + index + triggerStringLength).then(
				async () => {
					let testeditor = await hx.window.getActiveTextEditor();
					let selection = testeditor.selection;
					testeditor.edit(editBuilder => {
						editBuilder.replace(selection, userSelectd.rule)
					})
				})
		})
	} else {
		let selection = editor.selection;
		editor.edit(editBuilder => { editBuilder.replace(selection, userSelectd.rule) })
	}

}


//该方法将在插件禁用的时候调用（目前是在插件卸载的时候触发）
function deactivate() {

}
module.exports = {
	activate,
	deactivate
}